package com.css.fxfzmh.common.utils;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/fw/image")
public class ImageUtil {
    /**
     * 将某个路径下的图片装换成base64位
     * @param src
     * @return
     */
    public static String getImageBase(String src) {
        if(src==null||src==""){
            return "";
        }
        File file = new File(src);
        if(!file.exists()) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /**
     * 将base64编码转成图片格式并保存到本地，并返回虚拟路径
     * @param base64Info
     * @param fileName
     * @return
     */
    @RequestMapping("/image")
    @ResponseBody
    public Map<String, String> image(String base64Info, String fileName){
        //String targetDirectory = configBeanValue.wordImage;
        //String virtualPath = configBeanValue.virtualPath;
        //确保图片名称的唯一性
        String filename = fileName + ".png";
        String imagePath = ImageUtil.class.getResource("/images").getPath() +"/"+filename;
       // String savePath = targetDirectory + File.separator + filename;
        base64Info = base64Info.split("base64,")[1];
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] data = decoder.decodeBuffer(base64Info);
            // 调整异常数据
            for (int i = 0; i < data.length; ++i) {
                if (data[i] < 0) {
                    data[i] += 256;
                }
            }
            OutputStream os = new FileOutputStream(imagePath);
            os.write(data);
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        Map<String,String> map = new HashMap<>();
        map.put("imageUrl",imagePath);
        return map;
    }
}
